#include "../inc/FileReader.h"

bool FileReader::setrFileURL(char* fileURL)
{
	bool setFileURLResult = true;
	this->FileURL = fopen(fileURL,"r");
	if(!this->FileURL)
	{
		setFileURLResult=false;
		std::cerr<<"Can not open file: "<<fileURL<<std::endl;
	}
	return setFileURLResult;
}
bool FileReader::Read(MatrixData* matrix_from_file) const
{
	bool readFromFileResult = true;
	int curentSimvASSCI = -1;
	int matrixRowlength = -1;
	MatrixValue curentNumber;
	std::string strNumb;
	MatrixRow matrix_from_file_row;
	
	if(!FileURL)
	{
		readFromFileResult = false;
		std::cerr<<"Can not read from file."<<std::endl;		
	}

	do
	{
		curentSimvASSCI=fgetc(FileURL);
		if(curentSimvASSCI>='0'&&curentSimvASSCI<='9')
		{
			strNumb.push_back(curentSimvASSCI);
		}
		else
		{
			if(curentSimvASSCI==' '||curentSimvASSCI==EOF||curentSimvASSCI=='\n')
			{
				curentNumber=atoi(strNumb.c_str());
				matrix_from_file_row.push_back(curentNumber);
				strNumb.clear();				
			}			
			if(curentSimvASSCI==EOF||curentSimvASSCI=='\n')
			{
				if(matrixRowlength == -1)//Check length each matrix rows from file
				{
					matrixRowlength=matrix_from_file_row.size();
				}
				else
				{
					if(matrixRowlength!=matrix_from_file_row.size())
					{
						readFromFileResult = false;
						std::cerr<<"Incorrect matrix format in file."<<std::endl;						
					}
				}
				matrix_from_file->push_back(matrix_from_file_row);
				matrix_from_file_row.clear();
			}
			else
			{
				if(curentSimvASSCI!=' ')
				{
					readFromFileResult = false;
					std::cerr<<"Incorrect matrix format in file."<<std::endl;					
				}
			}			
		}
	}
	while(curentSimvASSCI!=EOF);
	
	return readFromFileResult;
}

FileReader::FileReader(void)
{
	this->FileURL=NULL;
}

FileReader::~FileReader(void)
{
	if(FileURL)
	{
		fclose (FileURL);
	}
}
